package com.xjgc.ws.mes.dao;

import com.xjgc.common.config.DbConn;
import com.xjgc.ws.util.CheckData;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;

/**
 * 运监
 */
@Component
public class ZxjEip2cScbom {
    @Autowired
    DbConn db;
    @Autowired
    CheckData cData;
    public String work(String xmlData) throws SQLException {

        String rs = null;
        PreparedStatement inPst = null;
        PreparedStatement selectPst = null;

        //定义执行SQL脚本
        String inSql = "insert into zxj_eip_2c_scbom values(?,?,?,?,?,?,?,?,?,?,?,?,?)";  //21插入SQL
        String selectSql = "select * from zxj_mes_matnr where MATNR = ?";
        //创建数据库连接
        inPst = db.getConnetion().prepareStatement(inSql);
        selectPst = db.getConnetion().prepareStatement(selectSql);
        int count=0;
        //解析xml文件
        Document doc = null;

        try {
            doc = DocumentHelper.parseText(xmlData);
            Element root = doc.getRootElement();
            Iterator<?> it = root.elementIterator();

            while(it.hasNext()) {

                Element element = (Element) it.next();

                inPst.setString(1, element.elementText("AUFNR"));
                inPst.setString(2, element.elementText("MATNR"));
                inPst.setString(3, element.elementText("RSPOS"));

                selectPst.setString(1,element.elementText("MATNR"));
                ResultSet resultSet = selectPst.executeQuery();
                String maktx = resultSet.getString("MAKTX");
                inPst.setString(4,maktx);//物料描述，关联到zxj_mes_matnr表的MAKTX字段

                inPst.setString(5, element.elementText("IDNRK"));
                inPst.setString(6, element.elementText("MAKTX"));
                inPst.setString(7, element.elementText("BDMNG"));
                inPst.setString(8, element.elementText("MEINS"));

                inPst.setString(9, "1");//成功标志
                inPst.setString(10, "1");//提示消息
                inPst.setString(11, element.elementText("VKORG"));//供应商编码
                inPst.setString(12, "1");//IOflag

                //插入更新数据
                int row = inPst.executeUpdate();
                if(row>0) {
                    count++;
                }
            }
            if (count>0) {
                rs = "0";//执行成功
            }
        } catch (DocumentException e1) {
            rs=e1.toString();//执行失败
            e1.printStackTrace();
        }
        //关闭连接
        inPst.close();
        db.closeCn();
        return rs;
    }
}
